package com.db.tenant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.db.core.vo.PageResult;
import com.db.core.vo.R;
import com.db.tenant.dto.TenantPageDto;
import com.db.tenant.entity.Tenant;

import com.db.tenant.mapper.TenantMapper;
import com.db.tenant.service.TenantService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 租户表 服务实现类
 * </p>
 *
 * @author db
 * @since 2023-10-29
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {

    @Override
    public PageResult pageList(TenantPageDto tenantPageDto) {
        //设置分页信息
        IPage iPage = new Page();
        iPage.setCurrent(tenantPageDto.getNow());
        iPage.setSize(tenantPageDto.getSize());
        //设置查询过滤条件
        QueryWrapper<Tenant> tenantQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(tenantPageDto.getName()))
            tenantQueryWrapper.like("name",tenantPageDto.getName());
        if (!StringUtils.isEmpty(tenantPageDto.getAccessKey())) {
            tenantQueryWrapper.like("access_key", tenantPageDto.getAccessKey());
        }
        //开始查询
        IPage iPage1 = baseMapper.selectPage(iPage, tenantQueryWrapper);
        //将数据封装到pageBean
        PageResult<Tenant> pageResult = new PageResult<>();
        pageResult.setTotal(iPage1.getTotal());
        pageResult.setPages(iPage1.getPages());
        pageResult.setList(iPage1.getRecords());
        return pageResult;
    }

    @Transactional
    @Override
    public R toggleEnable(String tenantID) {
        //查询当前enable状态
        Tenant tenant = baseMapper.selectById(tenantID);
        tenant.setEnable(3-tenant.getEnable());
        baseMapper.updateById(tenant);
        return R.ok("success");
    }
}
